
const express = require("express")
const app = express();
const path = require("path");

//处理body请求体的中间件
app.use(express.urlencoded())
app.use(express.json())

//查询学生信息接口
app.get("/user", (req, res) => {
    // console.log(req.query);
    //设置token
    const token = req.headers.token;
    if (!token) {
        return res.send({
            code: 10002,
            msg: "没有权限",
            data: null
        })
    }

    const {
        userId
    } = req.query;

    //如果查询失败
    if (userId !== "001") {
        return res.send({
            code: 10001,
            msg: "查询失败",
            data: null
        })
    }

    //查询成功 响应
    res.send({
        code: 10000,
        msg: "查询成功",
        data: {
            name: "李博",
            age: 18,
            sex: "男"
        }
    })

})


//定义一个延迟响应的接口
app.get('/userlazy', (req, res) => {
    setTimeout(() => {
        const {
            userId
        } = req.query

        if (userId !== '001') {
            return res.send({
                code: 10001,
                msg: '查询失败',
                data: null
            })
        }
        res.send({
            code: 1000,
            msg: '查询成功',
            data: {
                name: kk,
                age: 16,
                gender: '男'
            }
        })
    }, 5000);
})


app.post("/adduser", (req, res) => {
    console.log("adduser");
    console.log(req.body, "req.body");
    console.log(req.query, "req.query");
    const {
        name,
        age,
        sex
    } = req.body;

    if (!name || !age || !sex) {
        return res.send({
            code: 10001,
            mes: "添加失败",
            data: null
        })
    }

    res.send({
        code: 10000,
        mes: "添加成功",
        data: null
    })
})

//静态资源部署
// app.get('/1', (req, res) => {
//     const filePath = path.resolve(__dirname, "./03.创建axios实列.html");
//     res.sendFile(filePath);
// })
// app.get('/2', (req, res) => {
//     const filePath = path.resolve(__dirname, "./04.请求拦截器.html");
//     res.sendFile(filePath);
// })
// app.get('/3', (req, res) => {
//     const filePath = path.resolve(__dirname, "./05.响应拦截器.html");
//     res.sendFile(filePath);
// })
// app.get('/4', (req, res) => {
//     const filePath = path.resolve(__dirname, "./06.拦截器的异常处理.html");
//     res.sendFile(filePath);
// })
app.get('/5', (req, res) => {
    const filePath = path.resolve(__dirname, "./07.拦截器练习.html");
    res.sendFile(filePath);
})
app.get('/6', (req, res) => {
    const filePath = path.resolve(__dirname, "./08.拦截器练习2.html");
    res.sendFile(filePath);
})
app.get('/7', (req, res) => {
    const filePath = path.resolve(__dirname, "./09.取消请求.html");
    res.sendFile(filePath);
})

app.listen(5000, () => {
    console.log("服务器请求成功 请访问 http://127.0.0.1:5000");
})